﻿using System;
using System.Text;
using System.Linq;
using System.Timers;
using System.Net.Mail;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
using System.Collections.Generic;
using EmailMarketingCampaign;

namespace MailScheduler
{
    class Scheduler
    {
        EmailDAO emailDAO = new EmailDAO();
        private static int INTERVAL = 30 * 1000; // 30 sec
        private Timer t;

        public void startup()
        {
            t = new Timer(INTERVAL);
            t.Elapsed += new System.Timers.ElapsedEventHandler(theout);
            t.AutoReset = true;
            t.Enabled = true;
            t.Start();
            Console.WriteLine("Scheduler start");
        }

        public void stop()
        {
            t.Stop();
            t.Dispose();
            Console.WriteLine("Bye!");
        }

        private void theout(object source, System.Timers.ElapsedEventArgs e)
        {
            // TODO send mails
            try
            {
                List<EmailDTO> scheduledList = new List<EmailDTO>();
                scheduledList = emailDAO.RetriveAllEmailScheduled();
                for (int i = 0; i < scheduledList.Count; i++)
                {
                    int id = scheduledList[i].CampaignID;
                    string subject = scheduledList[i].Subject;
                    string body = scheduledList[i].Body;
                    string fromEmail = scheduledList[i].FromEmail;
                    string toEmail = scheduledList[i].ToEmail;
                    bool flag = emailDAO.SendMail(subject, body, fromEmail, toEmail);
                    if (flag == true)
                    {
                        emailDAO.UpdateSendStatues(id);
                        Console.Write("Send Successfully!");
                        
                    }
                    else
                    {
                        Console.Write("Failed to send!");
                    }
                }


            }
            catch (SqlException ex)
            {
                // Log the exception
                Console.WriteLine(ex);
            }

            // send
            Console.WriteLine("Schedule tracking mails!");
        }
    }
}
